package com.example.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class LoadApiHandler {
    private static final Logger logger = LoggerFactory.getLogger(LoadApiHandler.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ZuulProperties zuulProperties;

    @EventListener({ContextRefreshedEvent.class})
    public void onApplicationEvent() {
        List<RouteInfo> routeInfos = jdbcTemplate.query("select * from t_sys_route", new BeanPropertyRowMapper<>(RouteInfo.class));
        ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
        for (RouteInfo routeInfo : routeInfos) {
            zuulRoute.setPath(routeInfo.getPath());
            zuulRoute.setUrl(routeInfo.getUrl());
            zuulRoute.setId(routeInfo.getCode());
            zuulProperties.getRoutes().put(routeInfo.getCode(), zuulRoute);
        }
        logger.info("加载配置{}", routeInfos.size());
    }
}
